package com.ws.demo.configuration;

import com.ws.demo.handler.DemoWebSocketHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

/**
 * 服务端WebSocket 配置类
 */
@Configuration
@EnableWebSocket // 更换其他方式
public class WebSocketConfiguration implements WebSocketConfigurer {

    /**
     * 注册 webSocketHandler
     * @param webSocketHandlerRegistry 登记对象
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        webSocketHandlerRegistry.addHandler(demoWebSocketHandler(), "/demo/ws")
                .addInterceptors(new HttpSessionHandshakeInterceptor()).setAllowedOrigins("*");
    }

    @Bean
    public DemoWebSocketHandler demoWebSocketHandler() {
        return new DemoWebSocketHandler();
    }
}
